#include "logindatabase.h"
#include <QtSql>
#include <QMessageBox>
#include <QVariant>

LoginDatabase::LoginDatabase()
{
    LoginDatabase::connect();
}

bool LoginDatabase::connect(){
    /*
    QSqlDatabase db;
    db = QSqlDatabase::addDatabase("QMYSQL"); //a
    db.setHostName("127.0.0.1");             //b
    db.setDatabaseName("test");              //c
    db.setUserName("root");                  //d
    db.setPassword("cout<<\"sore2002\"<<endl;");                //e
    */
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");//a
    db.setHostName("127.0.0.1");             //b
    db.setDatabaseName("test04");              //c
    db.setUserName("root");                  //d
    db.setPassword("123456");                //e
    if (db.open()) {
        return true;
    }
    else{
        QMessageBox::critical(0, QObject::tr("Database Error"), db.lastError().text());
        return false;
    }
}

bool LoginDatabase::addItem(QString in_UserName, QString in_Password){
    QSqlQuery query;
    QString str = QString("insert into AcconutInfo(Username, Password) value('%1','%2')").arg(in_UserName).arg(in_Password);
    /*
    query.prepare("insert into AcconutInfo(Username,Password) value(:in_UserName,:in_Password)");
    query.bindValue("in_UserName",in_UserName);
    query.bindValue("in_Password",in_Password);
    */
    if(!query.exec(str)){
        QMessageBox::critical(0, QObject::tr("Database Error-3"),
                              query.lastError().text());
        return false;
    }
    return true;
}

bool LoginDatabase::loginCheck(QString in_UserName, QString in_Password){
    QSqlQuery query;
    QString str = QString("select * from AccountInfo where Username = '%1'").arg(in_UserName);
    query.exec(str);
    QString str1;
    if(query.next())
        str1 = query.value(1).toString();
    if(str1 == in_Password){
        return true;
    }
    else{
        QMessageBox::critical(0, QObject::tr("Login failed."),
                              query.lastError().text());
        return false;
    }
}
